import Vue from 'vue';
import Popup from '../components/popup.vue';
import { mapMutations, mapGetters } from 'vuex';

export default {
    data() {
        return {
            clickLineId: null,//当前点击的管线ID
            hoverLineIndex: null,//当前悬停的管线ID 弃用
            hoverLineIndexs: {},//当前悬停的管线IDs

            tempLineLayerId: "tempLineLayerId",//临时线段图层
            tempLineSourceId: "tempLineSourceId",//临时线段数据源ID
            tempPointLayerId: "tempPointLayerId",//临时点位图层
            tempPointSourceId: "tempPointSourceId",//临时点数据源ID
            popupTemp: null,//临时弹窗

            tempStorePopupData: {},//临时存储弹窗数据
            tempTimeOut: null,
        };
    },
    methods: {
        // 设置图层鼠标响应事件
        loadVectorLayerMouseEvent(layerId, layerSourceId, polygonType) {
            let that = this;
            // 1961609071924613120-point，1961609071924613120, xxx,
            // console.log("layerId1, layerSourceId, polygonType", layerId, layerSourceId, polygonType)
            this.map.on('mousemove', layerId, (e) => {
                if (!that.getIsVectorLayerActive) return;
                // console.log("layerId2, layerSourceId, polygonType", layerId, layerSourceId, polygonType)
                if (e.features.length > 0) {
                    // console.log(e.features);
                    if (that.hoverLineIndexs[layerId] !== undefined && that.hoverLineIndexs[layerId].length !== 0) {
                        that.hoverLineIndexs[layerId].forEach((item, index) => {
                            let has = false;
                            for (let i = 0; i < e.features.length; i++) {
                                if (e.features[i].id === item) {
                                    has = true;
                                }
                            }
                            if (!has) {
                                console.log("删除当前元素：", layerId + '-' + item)
                                // 删除当前元素
                                // that.removeTemp(layerId, item);

                                that.map.setFeatureState(
                                    { source: layerSourceId, id: item },
                                    { hover: false }
                                );
                            }
                        })
                    }

                    that.hoverLineIndexs[layerId] = [];
                    e.features.forEach((item, index) => {
                        that.hoverLineIndexs[layerId][index] = item.id;
                        that.map.setFeatureState(
                            { source: layerSourceId, id: item.id },
                            { hover: true }
                        );

                        // let geometry = item.geometry;
                        // if (polygonType === 'line') {
                        //     that.createTempLine(geometry, { layerId: layerId, itemId: item.id })
                        // } else {
                        //     that.createTempPoint(geometry, { layerId: layerId, itemId: item.id });
                        // }
                    })
                }
            });

            this.map.on('click', layerId, (e) => {
                if (!that.getIsVectorLayerActive) return;
                console.log("e.features[n]", e.features)
                // 处理弹出多个窗口的情况
                // todo

                // 组装图层属性
                let props = [];
                e.features.forEach((item, index) => {
                    let primaryKey = '编号'
                    for (let i = 0; i < that.getCurrentProjectConfig.data.length; i++) {
                        if (that.getCurrentProjectConfig.data[i].layerId === item.layer.source) {
                            // 将layerList字段保存下来
                            primaryKey = this.getCurrentProjectConfig.data[i].primaryKey;
                        }
                    }
                    props[item.layer.source + '-' + item.properties[primaryKey]] = item;
                })
                console.log("props", props)

                let coordinates = [e.lngLat.lng, e.lngLat.lat];
                // that.createPopUp(e.features[0].properties);//第二步中的创建内容的方法
                that.createPopUp(props, coordinates);//第二步中的创建内容的方法

                // new mapboxgl.Popup({ closeButton: true, className: 'popup_temp_container' })
                //     .setLngLat(coordinates)
                //     .setDOMContent(that.popupTemp)
                //     .addTo(that.map);
            });

            this.map.on('mouseleave', layerId, (e) => {
                if (!that.getIsVectorLayerActive) return;
                if (that.hoverLineIndexs[layerId] !== undefined && that.hoverLineIndexs[layerId].length !== 0) {
                    that.hoverLineIndexs[layerId].forEach((item, index) => {
                        that.map.setFeatureState(
                            { source: layerSourceId, id: item },
                            { hover: false }
                        );
                        console.log("清除图形：", layerId, item, that.hoverLineIndexs[layerId].length);
                        // that.removeTemp(layerId, item);
                    })
                    that.hoverLineIndexs[layerId] = [];
                }
            });
        },
        // 创建弹出窗口
        createPopUp(properties, coordinates) {
            let that = this;

            Object.keys(properties).forEach((item, index) => {
                that.tempStorePopupData[item] = properties[item];
            })

            if (this.tempTimeOut !== null)
                return;
            this.tempTimeOut = setTimeout(() => {
                console.log("输出组装的内容", that.tempStorePopupData)
                let a = that.tempStorePopupData;
                const p = Vue.extend(Popup);
                let vm = new p({
                    propsData: {
                        obj: {
                            // isShowName: true,
                            // name1: "测试参数传递...",
                            // properties
                            projectConfig: that.getCurrentProjectConfig,
                            properties: a
                        }
                    },//传参
                });
                vm.$mount();//挂载
                that.popupTemp = vm.$el;

                new mapboxgl.Popup({ closeButton: true, className: 'popup_temp_container' })
                    .setLngLat(coordinates)
                    .setDOMContent(that.popupTemp)
                    .addTo(that.map);

                that.tempStorePopupData = {};
                that.tempTimeOut = null;
            }, 20);

            // const p = Vue.extend(Popup);
            // let vm = new p({
            //     propsData: {
            //         obj: {
            //             // isShowName: true,
            //             // name1: "测试参数传递...",
            //             properties
            //         }
            //     },//传参
            // });
            // vm.$mount();//挂载
            // this.popupTemp = vm.$el;
        },
        // 卸载图层鼠标事件
        unloadVectorLayerMouseEvent(layerId, layerSourceId) {
            let that = this;
            this.map.off('mousemove', layerId);
            this.map.off('mouseleave', layerId);
        },
        // 创建临时线段
        createTempLine(geometry, options = {}) {
            let that = this;
            const map = this.map;
            // 合并默认选项
            const { color = 'rgba(23, 116, 223, 1)', width = 20 } = options;

            // 创建GeoJSON特征
            const lineFeature = {
                type: 'Feature',
                geometry: geometry
            };

            let uniqueId = options.layerId + '-' + options.itemId;

            // 检查源是否存在
            if (!map.getSource(uniqueId)) {
                console.log("创建新数据源line", uniqueId)
                // 创建新源
                map.addSource(uniqueId, {
                    type: 'geojson',
                    data: {
                        type: 'FeatureCollection',
                        features: [lineFeature]
                    }
                });

                // 创建新图层
                map.addLayer({
                    id: uniqueId,
                    type: 'line',
                    source: uniqueId,
                    paint: {
                        'line-color': color,
                        'line-width': width
                    }
                });
            } else {
                console.log("更新现有源line", uniqueId)
                // 更新现有源
                const source = map.getSource(uniqueId);
                source.setData({
                    type: 'FeatureCollection',
                    features: [lineFeature]
                });

                // 更新图层样式
                map.setPaintProperty(uniqueId, 'line-color', color);
                map.setPaintProperty(uniqueId, 'line-width', width);
            }
        },
        // 创建临时点
        createTempPoint(geometry, options = {}) {
            // todo
            let that = this;
            const map = this.map;
            // 合并默认选项
            const { color = 'rgba(23, 116, 223, 1)', radius = 5 } = options;

            // 创建GeoJSON特征
            const pointFeature = {
                type: 'Feature',
                geometry: geometry
            };

            let uniqueId = options.layerId + '-' + options.itemId;

            // 检查源是否存在
            if (!map.getSource(uniqueId)) {
                console.log("创建新数据源", uniqueId)
                // 创建新源
                map.addSource(uniqueId, {
                    type: 'geojson',
                    data: {
                        type: 'FeatureCollection',
                        features: [pointFeature]
                    }
                });

                // 创建新图层
                map.addLayer({
                    id: uniqueId,
                    type: 'circle',
                    source: uniqueId,
                    paint: {
                        'circle-color': color,
                        'circle-radius': radius
                    }
                });
            } else {
                // 更新现有源
                console.log("更新现有数据源", uniqueId)
                const source = map.getSource(uniqueId);
                source.setData({
                    type: 'FeatureCollection',
                    features: [pointFeature]
                });

                // 更新图层样式
                map.setPaintProperty(uniqueId, 'circle-color', color);
                map.setPaintProperty(uniqueId, 'circle-radius', radius);
            }
        },
        // 移除临时图形
        removeTemp2() {
            const map = this.map; //

            // 检查图层是否存在
            if (map.getLayer(this.tempLineLayerId)) {
                map.removeLayer(this.tempLineLayerId);
            }

            // 检查源是否存在
            if (map.getSource(this.tempLineSourceId)) {
                map.removeSource(this.tempLineSourceId);
            }

            // 检查图层是否存在
            if (map.getLayer(this.tempPointLayerId)) {
                map.removeLayer(this.tempPointLayerId);
            }

            // 检查源是否存在
            if (map.getSource(this.tempPointSourceId)) {
                map.removeSource(this.tempPointSourceId);
            }
        },
        // 移除临时图形
        removeTemp(layerType, layerId) {
            const map = this.map; //
            let uniqueId = layerType + '-' + layerId;
            console.log("xxxxx---->删除图层", uniqueId)
            // if (map.getSource(uniqueId)) {
            //     map.removeSource(uniqueId);
            //     console.log("xxxxx---->删除图层成功", uniqueId)
            // }
            if (map.getLayer(uniqueId)) {
                map.removeLayer(uniqueId);
                console.log("xxxxx---->删除图层成功", uniqueId)
            }
        },
    },
    computed: {
        ...mapGetters(['getIsVectorLayerActive']),
    },
    created() {

    },
    destroyed() {

    }
}
